package com.luoxin.servicemap.remote;

import com.alibaba.fastjson.JSONObject;
import com.luoxin.internalcommon.constant.AmapConfigConstants;
import com.luoxin.internalcommon.dto.ResponseResult;
import com.luoxin.internalcommon.request.PointDTO;
import com.luoxin.internalcommon.request.PointRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.net.URI;

@Slf4j
@Service
public class PointClient {
    @Value("${amap.key}")
    private String mapKey;
    @Value("${amap.sid}")
    private String sid;

    @Autowired
    private RestTemplate restTemplate;
    public ResponseResult upload(PointRequest pointRequest) {

        StringBuilder url = new StringBuilder();
        url.append(AmapConfigConstants.POINT_UPLOAD);
        url.append("?");
        url.append("key="+mapKey);
        url.append("&");
        url.append("sid="+sid);
        url.append("&");
        url.append("tid="+pointRequest.getTid());
        url.append("&");
        url.append("trid="+pointRequest.getTrid());
        url.append("&");
        url.append("points=");
        PointDTO[] points = pointRequest.getPoints();
        url.append("%5B");
        for (PointDTO p : points) {
            url.append("%7B");
            String locatetime = System.currentTimeMillis()+"";//p.getLocatetime();
            String location = p.getLocation();
            url.append("%22location%22");
            url.append("%3A");
            url.append("%22"+location+"%22");
            url.append("%2C");

            url.append("%22locatetime%22");
            url.append("%3A");
            url.append(locatetime);

            url.append("%7D");
        }
        url.append("%5D");

        ResponseEntity<String> stringResponseEntity = restTemplate.postForEntity(URI.create(url.toString()), null, String.class);
        String body = stringResponseEntity.getBody();
        log.info("高德地图轨迹点上传结果:{}", body);
        // {"errcode":20100,"errmsg":"OK","errdetail":"PARTIAL_SUCCESS","data":{"errorpoints":[{"_param_err_info":"locatetime","_err_point_index":0,"location":"116.38,39.98","locatetime":1761617612}]}}
        JSONObject result = JSONObject.parseObject(body);
        String errcode = result.getString("errcode");
        if (!"10000".equals(errcode)){
            String errmsg = result.getString("errmsg");
            return ResponseResult.fail(Integer.valueOf(errcode), errmsg);
        }
        return ResponseResult.success();
    }
}
